package com.tughluq.smsredirector

import android.Manifest
import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Build
import android.os.Bundle
import android.telephony.SubscriptionInfo
import android.telephony.SubscriptionManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.Switch
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*

class MainActivityState : IState {
    var title = "SMS redirection tool by Tughluq software technologies"
    var availableCards = arrayOf<SubscriptionInfo>()
}

class MainActivity : AppCompatActivity(), IStateful<MainActivityState> {
    override val state by lazy { MainActivityState() }
    var _adapter: BaseAdapter? = null
    override fun setState(action: MainActivityState.() -> Unit) {
        state.action()
        titleTextView.text = state.title
        enableSwitch.isChecked = myAppConfig.enabled
//        cardsListView.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)
        _adapter?.notifyDataSetChanged()
        startOrStopService()
    }

    companion object {
        val PERMISSION_REQUEST_CODE = 0
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val granted = checkSelfPermission(Manifest.permission.RECEIVE_SMS) == PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED
            if (!granted) {
                requestPermissions(arrayOf(Manifest.permission.RECEIVE_SMS, Manifest.permission.READ_PHONE_STATE), PERMISSION_REQUEST_CODE)
                return
            }
        }

        state.availableCards = (getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE) as SubscriptionManager).activeSubscriptionInfoList.toTypedArray()

        enableSwitch.setOnCheckedChangeListener {_, checked ->
            setState {
                myAppConfig = AppConfig(checked, myAppConfig.selectedSlot)
            }
        }

        _adapter = object : BaseAdapter() {
            override fun getItem(position: Int): Any = state.availableCards[position]
            override fun getItemId(position: Int): Long = state.availableCards[position.toInt()].simSlotIndex.toLong()
            override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
                var view = convertView ?: LayoutInflater.from(this@MainActivity).inflate(R.layout.card_list_item, null, false)
                val item = state.availableCards[position]
                view.findViewById<TextView>(R.id.number).text = item.number
                view.findViewById<TextView>(R.id.serviceProvider).text = item.displayName
                view.findViewById<ImageView>(R.id.icon).setImageBitmap(item.createIconBitmap(this@MainActivity))
                view.background = if (myAppConfig.selectedSlot == item.simSlotIndex) ColorDrawable(Color.parseColor("#008376")) else ColorDrawable(Color.TRANSPARENT)
                view.setOnClickListener {
                    setState {
                        myAppConfig = AppConfig(myAppConfig.enabled, item.simSlotIndex)
                    }
                }
                return view
            }
            override fun getCount(): Int = state.availableCards.count()
        }
        cardsListView.adapter = _adapter

        setState {  }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.contains(PackageManager.PERMISSION_DENIED)) {
                setState {
                    title = "Permission request failed, please give me receive SMS permission."
                }
            }
        }
    }
}
